package com.efounder.form.upload;

import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.widget.Toast;

import com.efounder.mobilecomps.R;
import com.efounder.util.AppContext;
import com.efounder.util.DialogUtil;
import com.pansoft.library.upload.UploadThreadPoolUtils;
import com.pansoft.library.utils.NetUtil;
import com.pizidea.imagepicker.ui.LoadingDataUtilBlack;

import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * Created by apple on 2017/12/14.
 */

public class UploadManager {
    private Context mContext;
    private UploadTask task;
    private UploadListener listener;
    private UploadSuccessListener successListener;

    private UploadMultiSuccessListener successMultiListener;
    public Handler handler = new Handler();
    public static HashMap<String, ImageUploadInfo> UPLOAD_INFO_HASHMAP = new HashMap<>();
    public static LinkedHashMap<String, String> urlLinkedHashMap;
    public HashMap forconference = new HashMap();

    private static UploadManager instance = new UploadManager();
    private ImageUploadInfo ImageUploadInfo;
    private boolean ISREMANDED;


    public static UploadManager getInstance() {
        return instance;
    }

    public void addUplaodListener(UploadListener listener) {
        this.listener = listener;
    }

    public void addUploadSucdessListener(UploadSuccessListener listener) {
        this.successListener = listener;
    }

    public void addUploadMultiSucdessListener(UploadMultiSuccessListener listener) {
        this.successMultiListener = listener;
    }

    public void addUploadInfo(String id, ImageUploadInfo info) {
        UPLOAD_INFO_HASHMAP.put(id, info);
    }


    public void notifyObservesUpload(final String id) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                listener.update(id);
            }
        });
    }

    public void notifyUploadSuccess(final LinkedHashMap<String, String> urlLinkedHashMap) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (null != successListener)
                    successListener.update(urlLinkedHashMap);
            }
        });
    }

    public void notifyUploadSuccess(final HashMap<String, String> hashMap) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (successMultiListener != null) {
                    successMultiListener.update(hashMap);
                }
            }
        });
    }

    public void notifyUploadError(){
        handler.post(new Runnable() {
            @Override
            public void run() {
                if(null != successListener){
                    successListener.uploadError();
                }
            }
        });
    }

    public void notifyMutiUploadError(){
        handler.post(new Runnable() {
            @Override
            public void run() {
                if(null != successMultiListener){
                    successMultiListener.uploadError();
                }
            }
        });
    }


    public void upload(final String id, final String path) {
        if (!NetUtil.isNetAvailable(mContext)) {
            if (!ISREMANDED){
                Toast.makeText(mContext, R.string.common_text_please_check_your_network, Toast.LENGTH_SHORT).show();
                LoadingDataUtilBlack.dismiss();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if(null != successListener){
                            successListener.uploadError();
                        }
                        if(null != successMultiListener){
                            successMultiListener.uploadError();
                        }
                    }
                });
            }

        } else if (ImageUploadInfo.isUploadOnGPRS() || NetUtil.isWIFIActivate(mContext)) {
            downloadAfterJudge(id, path);
        } else {
            //如果已经提醒，不会每个都提醒
            if (!ISREMANDED) {
                ISREMANDED = true;
                DialogUtil.showDialog(mContext, mContext.getResources().getString(R.string.mobilecomps_dataman),
                        mContext.getResources().getString(R.string.mobilecomps_dataman1),
                        mContext.getResources().getString(R.string.common_text_continue), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ImageUploadInfo.setUploadOnGPRS(true);
                        downloadAfterJudge(id, path);

                    }
                }, AppContext.getInstance().getResources().getString(R.string.common_text_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ImageUploadInfo.setUploadOnGPRS(false);
                    }
                });
            } else {
                downloadAfterJudge(id, path);
            }
        }

    }

    private void downloadAfterJudge(String id, String path) {
//        task = new DownloadTask(id, mContext, url, fileName, desFilePath,cloudBaseUrl);
//        boolean execute = ThreadPoolUtils.execute(task);
//        if (!execute) {
//            // 等待下载
//            task.setState(State.DOWNLOAD_WAIT);
//        }
        task = new UploadTask(id);
        boolean execute = UploadThreadPoolUtils.execute(task);
        if (!execute) {
            // 等待下载
            task.setState(UploadState.UPLOAD_WAIT);
        }
    }

    /**
     * 任务在等待状态下 删除下载任务
     *
     * @param id
     */
    public void deleteQueueTask(String id) {
        ImageUploadInfo downloadInfo = UPLOAD_INFO_HASHMAP.get(id);
        boolean cancelWaitTask = UploadThreadPoolUtils.cancelWaitTask(id);
        if (cancelWaitTask) {
            ImageUploadInfo.setState(UploadState.UPLOAD_NOT);
//            notifyObserves(id);
            notifyObservesUpload(id);
            //    DOWNLOAD_INFO_HASHMAP.remove(id);
        }
//        FileEntity.saveEntityByAppId(downloadInfo, mContext);
//        FileEntity.deleteEntity(downloadInfo, mContext);
    }

    /**
     * 退出后 取消下载
     */
//    public void cancelTask() {
//        for (int i = 0; i < urlList.size(); i++) {
//            if (null != task) {
//                task.cancel(urlList.get(i));
//                deleteQueueTask(idList.get(i));
//            }
//        }
//        if (DOWNLOAD_INFO_HASHMAP.size() != 0) {
//            DOWNLOAD_INFO_HASHMAP.clear();
//        }
//    }


    /**
     * 设置当前状态
     *
     * @param id
     * @param state
     */
    public void setState(String id, int state) {
        UPLOAD_INFO_HASHMAP.get(id).setState(state);
    }

    public boolean handleClick(String id, Context context, String path) {
        boolean netAvailable = isNetAvailable(context);
        this.mContext = context;
        ImageUploadInfo = UPLOAD_INFO_HASHMAP.get(id);
        if (netAvailable) {

//        addInformation(id, url, fileName, desFilePath);
            if (ImageUploadInfo != null) {

                switch (ImageUploadInfo.getState()) {
                    case UploadState.UPLOAD_COMPLETED:
                        // 已经下载完成
                        break;
                    case UploadState.UPLOAD_STOP:
                        // 暂停
                    case UploadState.UPLOAD_ERROR:
                        // 出错，重试
                    case UploadState.UPLOAD_NOT:
                        // 未下载
                        UploadManager.getInstance().upload(ImageUploadInfo.getLocalPath(), path);
                        break;
                    case UploadState.UPLOAD_WAIT:
                        // 线程池已满，应用添加到等待队列，用户点击后取消下载
//                UploadManager.getInstance().deleteQueueTask(ImageUploadInfo.getLocalPath());
                        break;
                    case UploadState.UPLOADING:
                        // 未出现异常，显示下载进度，点击暂停
//                        UploadManager.getInstance().setState(ImageUploadInfo.getLocalPath(), UploadState.UPLOAD_STOP);
                        break;
                }
            }

        } else {
            Toast.makeText(context, R.string.common_text_network_error, Toast.LENGTH_SHORT).show();
            if (null != ImageUploadInfo)
                ImageUploadInfo.setState(UploadState.UPLOAD_NOT);

            handler.post(new Runnable() {
                @Override
                public void run() {
                    if(null != successListener){
                        successListener.uploadError();
                    }
                    if(null != successMultiListener){
                        successMultiListener.uploadError();
                    }
                }
            });
        }
        return netAvailable;
    }

    //    private void addInformation(String id, String url, String fileName, String desFilePath) {
//        urlList.add(url);
//        idList.add(id);
//        fileNameList.add(fileName);
//        desFilePathList.add(desFilePath);
//    }
    public boolean isNetAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isAvailable();
    }

    public interface UploadListener {
        void update(String id);
    }

    public interface UploadSuccessListener {
        void update(LinkedHashMap<String, String> urlLinkedHashMap);
        void uploadError();
    }

    public interface UploadMultiSuccessListener {
        void update(HashMap<String, String> hashMap);
        void uploadError();
    }
}
